﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net;
using PersonalWebSite.Models;
using PersonalWebSite.Models.Admin;
using System.Web.Script.Serialization;
using System.Web.Caching;

namespace PersonalWebSite.Common
{
    /// <summary>
    /// Defines the VideoManager
    /// </summary>
    public class VideoManager
    {
        #region Variables
        private static readonly ILog logger = LogManager.GetLogger(typeof(VideoManager));
        private const string dataFileName = "Videos.json";
        protected const int pageSize = 10;
        private const string cacheKeyVideosFeed = "VideosFeed";
        protected static readonly TimeSpan videosCacheDuration = TimeSpan.FromHours(2);
        #endregion

        #region Constructor
        /// <summary>
        /// Inits the class
        /// </summary>
        static VideoManager()
        {
            log4net.Config.XmlConfigurator.Configure();
        }
        #endregion

        /// <summary>
        /// Fetches the videos
        /// </summary>
        /// <returns>Video Items</returns>
        public static VideosViewModel FetchVideos(int pageIndex = 0)
        {
            VideosViewModel model = Cache.CacheItem(cacheKeyVideosFeed, () => FetchVideosFromDataFile(), new CacheDependency(HttpContext.Current.Server.MapPath("~/Data/" + dataFileName)), null);

            int pageCount = model.Items.Count() / (pageSize - 1) + 1;
            pageIndex = pageIndex < 0 ? 0 : pageIndex > pageCount - 1 ? pageCount - 1 : pageIndex;
            model.ItemsToDisplay = model.Items.Skip(pageIndex * pageSize).Take(pageSize).ToArray();

            return model;
        }

        #region Helper Methods
        /// <summary>
        /// Fetches the videos from the data file
        /// </summary>
        /// <returns>Video Items</returns>
        private static VideosViewModel FetchVideosFromDataFile()
        {
            try
            {
                VideosViewModel model = new JavaScriptSerializer().Deserialize<VideosViewModel>(FileDataManager.LoadFileInfo(dataFileName).Content);
                model.Items = model.Items.OrderByDescending(i => i.Date).ToArray();
                return model;
            }
            catch (Exception ex)
            {
                string message = string.Format("An error occured while trying to fetch the videos from data file \"{0}\".", dataFileName);
                logger.Error(message, ex);
                throw;
            }
        }
        #endregion
    }
}